package com.etool.action.curd;


import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;

import com.etool.modules.curd.service.CurdService;
import com.etool.modules.curd.util.CurdConfigUtil;
import com.opensymphony.xwork2.ActionSupport;
public class ReadAction extends ActionSupport{
	private HttpServletRequest request=ServletActionContext.getRequest();
	private HttpServletResponse response=ServletActionContext.getResponse();
	
	private String target="auth_menu";

	private CurdService curdService;

	private int total=10;
	
	//页大小
	private int rows;
	//页数
	private int page;

	
	@Action(value="read")
	public String read() throws IOException
	{
		CurdConfigUtil.setSecondJdbc(curdService, target);
		
		int  offset=(page - 1) * rows;
		
		//动态获取参数
		Map<String, Object> searchParams=new HashMap<String, Object>();
		
		Enumeration<String> params = request.getParameterNames();
		
		List<String> columns=curdService.columns(target);
		
		while (params.hasMoreElements()) {
			String param=params.nextElement();
			if(columns.contains(param))
			{
				searchParams.put(param,request.getParameter(param));
			}
		}
		
		//查询
		List<Map<String, Object>> row=curdService.read(target, searchParams, offset, rows,null);
		
		//总记录数
		total=curdService.count(target,null);
		
		CurdConfigUtil.disableSecondJdbc(curdService);
		Map<String, Object> res=new HashMap<String, Object>();
		res.put("total", total);
		res.put("rows", row);
		response.setContentType("text/html;charset=utf-8");
		response.getWriter().write(JSONObject.fromObject(res).toString());
		response.getWriter().flush();
		return NONE;
	}
	
	public String getTarget() {
		return target;
	}

	public void setTarget(String target) {
		this.target = target;
	}
	
	public int getTotal() {
		return total;
	}


	public void setTotal(int total) {
		this.total = total;
	}


	
	public CurdService getCurdService() {
		return curdService;
	}

	public void setCurdService(CurdService curdService) {
		this.curdService = curdService;
	}

	public int getRows() {
		return rows;
	}

	public void setRows(int rows) {
		this.rows = rows;
	}

	public int getPage() {
		return page;
	}

	public void setPage(int page) {
		this.page = page;
	}

}
